﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace AdminSystem.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "v1")]
    public class UploadFileController : ControllerBase
    {
        private readonly IWebHostEnvironment environment;

        public UploadFileController(IWebHostEnvironment environment)
        {
            this.environment = environment;
        }

        /// <summary>
        /// 上传文件  /UploadFiles/images/2025/202502/202502131110356.jpg
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            var FileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{Path.GetExtension(file.FileName)}";

            var FilePath = $"/images/{DateTime.Now.Year}/{DateTime.Now.ToString("yyyyMM")}";

            Directory.CreateDirectory($@"{environment.WebRootPath}/{FilePath}");

            using (FileStream filestream = new FileStream($"{environment.WebRootPath}/{FilePath}/{FileName}", FileMode.Create))
            {
                await file.CopyToAsync(filestream);
            }

            return Ok(new
            {
                fileName = $"{FilePath}/{FileName}"
            });
        }
    }
}
